<template>
  <div class="way-of-life">
    <el-form :model="formData" :label-width="labelWidth" class="archive-form">
      <el-row :gutter="20">
        <!-- 吸烟情况 -->
        <el-col :span="8">
          <el-form-item
            :label="t('healthRecords.lifestyle.fields.smokingStatus')"
          >
            <el-input
              v-model="formData.smokingStatus"
              :placeholder="
                t('healthRecords.lifestyle.placeholders.smokingStatus')
              "
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>

        <!-- 饮酒情况 -->
        <el-col :span="8">
          <el-form-item
            :label="t('healthRecords.lifestyle.fields.drinkingStatus')"
          >
            <el-input
              v-model="formData.drinkingStatus"
              :placeholder="
                t('healthRecords.lifestyle.placeholders.drinkingStatus')
              "
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>

        <!-- 饮食习惯 -->
        <el-col :span="8">
          <el-form-item :label="t('healthRecords.lifestyle.fields.dietHabits')">
            <el-input
              v-model="formData.dietHabits"
              :placeholder="
                t('healthRecords.lifestyle.placeholders.dietHabits')
              "
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>

        <!-- 运动情况 -->
        <el-col :span="24">
          <el-form-item
            :label="t('healthRecords.lifestyle.fields.exerciseStatus')"
          >
            <el-input
              v-model="formData.exerciseStatus"
              :placeholder="
                t('healthRecords.lifestyle.placeholders.exerciseStatus')
              "
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 底部按钮 -->
      <div class="flex justify-end mt-4 gap-4">
        <el-button @click="handleEdit">{{
          t("healthRecords.lifestyle.buttons.edit")
        }}</el-button>
        <el-button type="primary" @click="handleSave">{{
          t("healthRecords.lifestyle.buttons.save")
        }}</el-button>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import type { HealthArchiveLifestyleInfo } from "@/api/health";
import { healthApi } from "@/api/health";
import { ElMessage } from "element-plus";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";

const props = defineProps<{
  archiveInfo?: HealthArchiveLifestyleInfo;
  requestSource?: number;
}>();

const emit = defineEmits<{
  (e: "update-success"): void;
}>();

// 国际化
const { t, locale } = useI18n();

// 是否处于编辑状态
const isEditing = ref(false);

// 根据语言状态动态调整label宽度
const labelWidth = computed(() => {
  // 英文状态下为130px，中文状态下为110px
  return locale.value === "en" ? "130px" : "110px";
});

// 表单数据
const formData = reactive<HealthArchiveLifestyleInfo>({
  archiveId: 0,
  smokingStatus: "",
  drinkingStatus: "",
  dietHabits: "",
  exerciseStatus: ""
});

// 监听props变化，更新表单数据
watch(
  () => props.archiveInfo,
  (newVal, oldVal) => {
    if (newVal) {
      console.log("生活方式信息数据更新:", {
        新数据: newVal,
        旧数据: oldVal,
        数据来源: props.requestSource
      });

      // 更新表单数据
      Object.assign(formData, newVal);

      console.log("生活方式表单数据已更新:", {
        档案ID: formData.archiveId,
        吸烟情况: formData.smokingStatus,
        饮酒情况: formData.drinkingStatus,
        饮食习惯: formData.dietHabits,
        运动情况: formData.exerciseStatus
      });
    } else {
      console.log("未接收到生活方式信息数据");
    }
  },
  { immediate: true }
);

// 编辑按钮点击事件
const handleEdit = () => {
  console.log("开始编辑生活方式信息", {
    当前表单数据: formData,
    编辑状态: isEditing.value
  });

  isEditing.value = true;
  ElMessage.success(t("healthRecords.lifestyle.messages.editMode"));

  console.log("生活方式编辑模式已开启");
};

// 验证表单数据
const validateForm = () => {
  if (!formData.archiveId) {
    ElMessage.error(t("healthRecords.lifestyle.messages.archiveIdRequired"));
    return false;
  }
  return true;
};

// 保存按钮点击事件
const handleSave = async () => {
  try {
    // 表单验证
    console.log("开始验证生活方式表单");
    if (!validateForm()) {
      console.log("生活方式表单验证失败");
      return;
    }
    console.log("生活方式表单验证通过");

    // 显示加载状态
    const loading = ElMessage({
      message: t("healthRecords.lifestyle.messages.saving"),
      duration: 0,
      type: "info"
    });

    // 构建提交数据，排除不属于HealthArchiveLifestyleInfo的字段
    const submitData: HealthArchiveLifestyleInfo = {
      archiveId: formData.archiveId,
      smokingStatus: formData.smokingStatus,
      drinkingStatus: formData.drinkingStatus,
      dietHabits: formData.dietHabits,
      exerciseStatus: formData.exerciseStatus,
      archiveLifestyleId: formData.archiveLifestyleId,
      requestSource: props.requestSource
    };

    console.log("准备提交的生活方式数据:", {
      基础字段: {
        archiveId: submitData.archiveId,
        archiveLifestyleId: submitData.archiveLifestyleId
      },
      生活方式信息: {
        吸烟情况: submitData.smokingStatus,
        饮酒情况: submitData.drinkingStatus,
        饮食习惯: submitData.dietHabits,
        运动情况: submitData.exerciseStatus
      },
      请求来源: props.requestSource
    });

    // 调用保存接口
    const response =
      await healthApi.getHealthArchiveUpdateLifestyle(submitData);

    // 关闭加载提示
    loading.close();

    console.log("生活方式保存接口响应:", response);
    // 触发父组件重新获取数据
    emit("update-success");
  } catch (error: any) {
    console.error("保存生活方式信息时发生异常:", {
      错误信息: error.message,
      错误堆栈: error.stack,
      当前数据: formData
    });
    ElMessage.error(t("healthRecords.lifestyle.messages.saveFailedRetry"));
  } finally {
    isEditing.value = false;
  }
};

onMounted(() => {
  console.log("WayOfLife组件已挂载", {
    初始表单数据: formData,
    传入的生活方式信息: props.archiveInfo,
    请求来源: props.requestSource,
    当前语言: locale.value
  });

  // 组件挂载完成后的额外初始化工作
  console.log("WayOfLife组件初始化完成");
});
</script>

<style lang="scss" scoped>
.way-of-life {
  padding: 20px 0;

  .archive-form {
    .el-form-item {
      margin-bottom: 18px;
    }

    :deep(.el-input),
    :deep(.el-select),
    :deep(.el-date-picker) {
      width: 100%;
    }
  }
}
</style>
